package com.imageim.yimirror.ui.fragment;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.RelativeLayout;

import com.imageim.yimirror.R;
import com.imageim.yimirror.base.BaseActivity;
import com.imageim.yimirror.base.BaseFragment;
import com.imageim.yimirror.bean.dailyPhoto.PhotoBgBean;
import com.imageim.yimirror.bean.dailyPhoto.SplitPhotoInfo;
import com.imageim.yimirror.bean.dailyPhoto.TryClothResultPhotoBean;
import com.imageim.yimirror.common.event.EventCode;
import com.imageim.yimirror.common.event.EventMessage;
import com.imageim.yimirror.common.network.NetUtil;
import com.imageim.yimirror.common.network.constants.NetConstants;
import com.imageim.yimirror.common.network.listener.NetCallback;
import com.imageim.yimirror.common.network.tool.ParamCreator;
import com.imageim.yimirror.common.ui.DragView;
import com.imageim.yimirror.common.ui.DragablePhotoView;
import com.imageim.yimirror.common.ui.MyFilterImageView;
import com.imageim.yimirror.common.ui.SceneManager;
import com.imageim.yimirror.common.ui.SpacesItemDecoration;
import com.imageim.yimirror.common.ui.SuperUIUtil;
import com.imageim.yimirror.common.ui.btn.BtnEffect;
import com.imageim.yimirror.common.ui.tip.TipUtil;
import com.imageim.yimirror.common.util.DownloadManager;
import com.imageim.yimirror.common.util.FileUtil;
import com.imageim.yimirror.common.util.UserUtil;
import com.imageim.yimirror.service.filter.MyFilterType;
import com.imageim.yimirror.ui.activity.TakeMemoryPhotoNewActivity;
import com.imageim.yimirror.ui.adapter.tryCloth.ChangePhotoBgListAdapter;
import com.imageim.yimirror.ui.adapter.tryCloth.FilterListAdapter;
import com.imageim.yimirror.ui.widght.LoadingView;
import com.martin.ads.omoshiroilib.util.BitmapUtils;

import org.apache.http.message.BasicNameValuePair;
import org.byteam.superadapter.OnItemClickListener;
import org.greenrobot.eventbus.EventBus;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import jp.co.cyberagent.android.gpuimage.GPUImage;
import jp.co.cyberagent.android.gpuimage.filter.GPUImageFilter;

/**
 * Change bg of photo
 * Created by Bruce.Zhou on 2018/11/22 12:03.
 * Email: 907160968@qq.com
 */
public class ChangePhotoBgFragment extends BaseFragment implements BtnEffect.OnSelectListener {
    @BindView(R.id.rv_bg_list)
    RecyclerView rvBgList;
    @BindView(R.id.draggablePhotoView)
    DragablePhotoView draggablePhotoView;
    @BindView(R.id.btn_sense)
    BtnEffect btnSense;
    @BindView(R.id.btn_filter)
    BtnEffect btnFilter;
    @BindView(R.id.rv_filter_list)
    RecyclerView rvFilterList;
    @BindView(R.id.filter_image_view)
    MyFilterImageView filterImageView;
    @BindView(R.id.drag_view)
    DragView dragView;
    @BindView(R.id.photo_container)
    RelativeLayout photoContainer;
    @BindView(R.id.loading_view)
    LoadingView loadingView;

    private ChangePhotoBgListAdapter bgListAdapter;
    private Bitmap noneBgBitmap; // 替换背景后的图
    private Bitmap originalBitmap; // 拍照裁剪后的图
    private Bitmap twoValueBitmap; // 二值图
    private TryClothResultPhotoBean memPhotoBean; // 留影列表项信息
    private GPUImage gpuImage;
    private int from;// 来自哪个页面，1来自拍照，2来自试穿留影列表
    private static final int MSG_QUERY_SPLIT_PHOTO = 101;
    private String originalBitmapLocalPath; // 原图在本地的保存路径

    private class MyHandler extends Handler {

        private WeakReference<ChangePhotoBgFragment> ref;

        public MyHandler(ChangePhotoBgFragment fragment) {
            ref = new WeakReference<>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {
            ChangePhotoBgFragment fragment = ref.get();
            if (fragment != null) {
                switch (msg.what) {
                    case MSG_QUERY_SPLIT_PHOTO:
                        removeMessages(MSG_QUERY_SPLIT_PHOTO);
                        fragment.getSplitedPhoto(); // 查询去背景处理是否完成
                        break;
                    default:
                        break;
                }
            }
        }
    } // MyHandler

    private MyHandler handler;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_change_bg;
    }

    private int[] bgResourceIds = new int[]{
            R.drawable.bga118, R.drawable.bga119, R.drawable.wall9, R.drawable.wall7
            , R.drawable.wall12, R.drawable.wall2, R.drawable.wall, R.drawable.bga100,
            R.drawable.bga117, R.drawable.bga107};

    private int[] bgSmallResourceIds = new int[]{R.drawable.bga118_small, R.drawable.bga119_small
            , R.drawable.wall9s, R.drawable.wall7s, R.drawable.wall12s, R.drawable.wall2s,
            R.drawable.wall_meitu_16, R.drawable.bga100_small, R.drawable.bga117_small,
            R.drawable.bga107_small};

    private int currIndex = 1;
    private boolean isFirstLoading = true;
    private boolean finishDownOriginal = false;
    private boolean finishDownNoneBgPhoto = false;
    private boolean finishDownTwoValuePhoto = false;

    @Override
    protected void initListener() {
        // init背景替换视图
        List<PhotoBgBean> photoBgList = new ArrayList();
        bgListAdapter = new ChangePhotoBgListAdapter(getContext(), photoBgList
                , R.layout.item_change_bg);
        SuperUIUtil.initRecylerView(getContext(), rvBgList, bgListAdapter)
                .orientation(SuperUIUtil.RecycleViewManager.HORIZONTAL)
                //                .anim(new SlideInRightAnimation())
                .onItemClick(new OnItemClickListener() {
                    @Override
                    public void onItemClick(View itemView, int viewType, int position) {
                        if (isFirstLoading && (currIndex != position)) {
                            return;
                        }
                        currIndex = position;
                        if (position == 0) { // 显示原图
                            draggablePhotoView.setOriginalShow(true);
                            filterImageView.setVisibility(View.GONE);
                            draggablePhotoView.resetUserPhoto(originalBitmap);
                        } else { // 显示滤镜和替换的背景
                            draggablePhotoView.setOriginalShow(false);
                            filterImageView.setVisibility(View.VISIBLE);
                            draggablePhotoView.setPhotoFrame(bgResourceIds[position - 1], noneBgBitmap);
                            updateFilterImage();
                            gpuImage.setFilter(getFilter(position - 1));
                        }
                        bgListAdapter.select(position);
                    }
                });
        rvBgList.addItemDecoration(new SpacesItemDecoration(8));
        for (int i = 0; i < bgResourceIds.length; i++) {
            PhotoBgBean bgBean = new PhotoBgBean();
            bgBean.setResourceId(bgResourceIds[i]);
            bgBean.setSmallResourceId(bgSmallResourceIds[i]);
            bgListAdapter.getData().add(bgBean);
        }
        bgListAdapter.notifyDataSetChanged();
        bgListAdapter.select(1);
        handler = new MyHandler(this);
        initView();
    }

    private void initView() {
        btnSense.setText("场景");
        btnFilter.setText("滤镜");
        btnSense.setSelectListener(this);
        btnFilter.setSelectListener(this);
        btnSense.setTextSize(20);
        btnFilter.setTextSize(20);
        btnSense.setSelected(true);
        initFilterViews();
        initDragView();
        loadFirstFilterBg();
    }

    /**
     * 根据进入入口的不同初始化应用的背景和滤镜
     */
    private void loadFirstFilterBg() {
        if (from == 1) { // from take mem pic.
            loadingView.setVisibility(View.VISIBLE);
            handler.sendEmptyMessageDelayed(MSG_QUERY_SPLIT_PHOTO, 400);
        } else { // from mem photo list.
            if (memPhotoBean != null) {
                if (!TextUtils.isEmpty(memPhotoBean.getBodySplitImage())) { // 第一张扫脸照片可能没那么快分离出抠图，所以可能为空
                    PhotoBgBean bgBean = new PhotoBgBean();
                    bgBean.setOriginalUrl(memPhotoBean.getPhotoUrl());
                    bgListAdapter.getData().add(0, bgBean);
                    bgListAdapter.notifyDataSetChanged();
                    bgListAdapter.select(1);
                    // 下载透明图和原图
                    String splitPhotoUrl = memPhotoBean.getBodySplitImage();
                    //                splitPhotoUrl = "http://dingyue.nosdn.127.net/1ALRulf7XHqBUl7aPt0SfBU=lsQmWeCfQ7wGRzlI6oI1Z1536206928376.jpeg";
                    DownloadManager.getInstance().download(splitPhotoUrl, "nonbgBitmap.jpg", new DownloadManager.DownloadCallback() {
                        @Override
                        public void onStart(String fileUrl) {
                            loadingView.setVisibility(View.VISIBLE);
                        }

                        @Override
                        public void onProgress(String fileUrl, float progress) {
                        }

                        @Override
                        public void onSuccess(String fileUrl, String localPath) {
                            Bitmap bitmap = BitmapUtils.loadBitmapFromFile(localPath);
                            if (bitmap != null) {
                                noneBgBitmap = bitmap;
                                applyBgFilter(0);
                            }
                            finishDownNoneBgPhoto = true;
                            if (isFirstLoading && finishDownNoneBgPhoto && finishDownOriginal && finishDownTwoValuePhoto) {
                                isFirstLoading = false;
                                loadingView.setVisibility(View.GONE);

                                //                            // white border
                                //                            Bitmap transTwoValueBitmap = BitmapUtils.getAroundTransBitmap(twoValueBitmap); // 去掉黑色的二值图
                                //                            noneBgBitmap = createWhiteBorderBitmap(transTwoValueBitmap, noneBgBitmap);
                                //                            twoValueBitmap.recycle();
                                //                            transTwoValueBitmap.recycle();
                                //                            applyBgFilter(0);
                            }
                        }

                        @Override
                        public void onFail(String fileUrl, int errorCode, String errorMsg) {
                            loadingView.setVisibility(View.GONE);
                        }
                    });
                    // 原图
                    String originalPhotoUrl = memPhotoBean.getPhotoUrl();
                    DownloadManager.getInstance().download(originalPhotoUrl, "originalBitmap.jpg", new DownloadManager.DownloadCallback() {
                        @Override
                        public void onStart(String fileUrl) {
                        }

                        @Override
                        public void onProgress(String fileUrl, float progress) {
                        }

                        @Override
                        public void onSuccess(String fileUrl, String localPath) {
                            setOriginalBitmapLocalPath(localPath);
                            Bitmap bitmap = BitmapUtils.loadBitmapFromFile(localPath);
                            if (bitmap != null) {
                                originalBitmap = bitmap;
                                gpuImage.setImage(BitmapFactory.decodeResource(getResources(), bgResourceIds[0]));
                            }
                            finishDownOriginal = true;
                            if (isFirstLoading && finishDownNoneBgPhoto && finishDownOriginal && finishDownTwoValuePhoto) {
                                isFirstLoading = false;
                                loadingView.setVisibility(View.GONE);
                                //                            // white border
                                //                            Bitmap transTwoValueBitmap = BitmapUtils.getAroundTransBitmap(twoValueBitmap); // 去掉黑色的二值图
                                //                            noneBgBitmap = createWhiteBorderBitmap(transTwoValueBitmap, noneBgBitmap);
                                //                            twoValueBitmap.recycle();
                                //                            transTwoValueBitmap.recycle();
                                //                            applyBgFilter(0);
                            }
                        }

                        @Override
                        public void onFail(String fileUrl, int errorCode, String errorMsg) {
                            loadingView.setVisibility(View.GONE);
                        }
                    });
                    // 下载二值图
                    String twoValuePhotoUrl = memPhotoBean.getTwoValueImage();
                    if (!TextUtils.isEmpty(twoValuePhotoUrl)) {
                        DownloadManager.getInstance().download(twoValuePhotoUrl, "twoValueBitmap.jpg", new DownloadManager.DownloadCallback() {
                            @Override
                            public void onStart(String fileUrl) {
                            }

                            @Override
                            public void onProgress(String fileUrl, float progress) {
                            }

                            @Override
                            public void onSuccess(String fileUrl, String localPath) {
                                Bitmap bitmap = BitmapUtils.loadBitmapFromFile(localPath);
                                if (bitmap != null) {
                                    twoValueBitmap = bitmap;
                                }
                                finishDownTwoValuePhoto = true;
                                if (isFirstLoading && finishDownNoneBgPhoto && finishDownOriginal && finishDownTwoValuePhoto) {
                                    isFirstLoading = false;
                                    loadingView.setVisibility(View.GONE);
                                    //                                // 显示白边图
                                    //                                if (twoValueBitmap != null) {
                                    //                                    Bitmap transTwoValueBitmap = BitmapUtils.getAroundTransBitmap(twoValueBitmap); // 去掉黑色的二值图
                                    //                                    noneBgBitmap = createWhiteBorderBitmap(transTwoValueBitmap, noneBgBitmap);
                                    //                                    twoValueBitmap.recycle();
                                    //                                    transTwoValueBitmap.recycle();
                                    //                                }
                                    //                                applyBgFilter(0);
                                }
                            }

                            @Override
                            public void onFail(String fileUrl, int errorCode, String errorMsg) {
                                loadingView.setVisibility(View.GONE);
                            }
                        });
                    }
                } else { // 第一张扫脸图还没抠图完成，所以需要在此去查询后台获取抠好的图
                    loadingView.setVisibility(View.VISIBLE);
                    handler.sendEmptyMessageDelayed(MSG_QUERY_SPLIT_PHOTO, 400);
                }
                //
            }
        }
    } // loadFirstFilterBg()


    private int queryCount = 0; // 查询透明背景次数

    private void getSplitedPhoto() {
        if (queryCount < 40) {
            queryCount++;
            // 如果来自拍照界面，则使用上传照片返回的photoNo,不然则使用photoList中的photoNo.
            String photoNo = from == 1 ? UserUtil.getMemPhotoNo() : memPhotoBean.getPhotoNo();
            String params = "photoNo=" + photoNo;
            NetUtil.getObject(getContext(), NetConstants.URL.GET_REMOVE_BG_PHOTO, params, new NetCallback<SplitPhotoInfo>() {
                @Override
                public void onStart() {
                }

                @Override
                public void onSuccess(SplitPhotoInfo result) {
                    if (result.getFlag() == 2) {
                        loadingView.setVisibility(View.GONE);
                        String cutImg = result.getBodyCutImg();
                        if (!TextUtils.isEmpty(cutImg)) {
                            noneBgBitmap = BitmapUtils.base64ToBitmap(cutImg);
                            applyBgFilter(0);
                            // white border
                            //                            Bitmap transUserBitmap = BitmapUtils.base64ToBitmap(cutImg); // 去掉背景的用户图片
                            //                            String twoValueBitmapStr = result.getTwoValueImageKey(); // 黑白二值图str
                            //                            Bitmap twoValueBitmap = BitmapUtils.base64ToBitmap(twoValueBitmapStr); // 黑白二值图
                            //                            Bitmap transTwoValueBitmap = BitmapUtils.getAroundTransBitmap(twoValueBitmap); // 去掉黑色的二值图
                            //
                            //                            noneBgBitmap = createWhiteBorderBitmap(transTwoValueBitmap, transUserBitmap);
                            //                            transTwoValueBitmap.recycle();
                            //                            transUserBitmap.recycle();
                            //                            twoValueBitmap.recycle();
                            //                            applyBgFilter(0);
                        } else {
                            TipUtil.show("背景分析失败，请稍后重试~");
                        }
                        isFirstLoading = false;
                    } else {
                        handler.sendEmptyMessageDelayed(MSG_QUERY_SPLIT_PHOTO, 400);
                    }
                }

                @Override
                public void onFail(int errorCode, String errorMsg) {
                    TipUtil.show(errorMsg + errorCode);
                    handler.sendEmptyMessageDelayed(MSG_QUERY_SPLIT_PHOTO, 400);
                }
            }, SplitPhotoInfo.class);
        } else {
            loadingView.setVisibility(View.GONE);
            isFirstLoading = false;
            TipUtil.show("背景替换失败，请稍后重试~");
        }
    } // getSplitedPhoto

    /**
     * 生成白边图
     *
     * @param whiteBgBitmap
     * @param noneBgBitmap
     * @return
     */
    private Bitmap createWhiteBorderBitmap(Bitmap whiteBgBitmap, Bitmap noneBgBitmap) {
        int dstWidth = noneBgBitmap.getWidth();
        int dstHeight = noneBgBitmap.getHeight();
        Bitmap dstBodyBitmap = Bitmap.createBitmap(dstWidth, dstHeight, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(dstBodyBitmap);
        Paint paint = new Paint();
        if (whiteBgBitmap != null) {
            canvas.drawBitmap(whiteBgBitmap, 0, 0, paint);
        }
        if (noneBgBitmap != null) {
            Bitmap tempBitmap = Bitmap.createScaledBitmap(noneBgBitmap, dstWidth - 20, dstHeight - 20, true);
            noneBgBitmap.recycle();
            canvas.drawBitmap(tempBitmap, 10, 10, paint);
        }
        return dstBodyBitmap;
    }

    private void initDragView() {
        dragView.setOnMyTouchListener(new DragView.OnMyTouchListener() {
            @Override
            public void onDown(float downX, float downY) {
                if (currIndex == 0) {
                    return;
                }
                draggablePhotoView.onTouchDown(downX, downY);
                //                gpuImage.deleteImage();
                //                filterImageView.setVisibility(View.INVISIBLE);
            }

            @Override
            public void onMove(float dx, float dy) {
                if (currIndex == 0) {
                    return;
                }
                draggablePhotoView.onTouchMove(dx, dy);
                updateFilterImage();
            }

            @Override
            public void onUp() {
                if (currIndex == 0) {
                    return;
                }
                updateFilterImage();
                filterImageView.setVisibility(View.VISIBLE);
            }

            @Override
            public void onScale(float scaleFactor) {
                draggablePhotoView.onScale(scaleFactor);
            }
        });

        //        draggablePhotoView.setPhotoFrame(0, originalBitmap);
        //        applyBgFilter(0);
    }

    private void updateFilterImage() {
        Bitmap resultbitmap = draggablePhotoView.getViewBitmap();
        gpuImage.deleteImage();
        gpuImage.setImage(resultbitmap);
    }

    /**
     * 初始化滤镜相关view
     */
    private void initFilterViews() {
        // filter list
        List<MyFilterType> filterTypeList = Arrays.asList(MyFilterType.values());
        FilterListAdapter filterAdapter = new FilterListAdapter(getContext(), filterTypeList, R.layout.item_myfilter_adapter);
        SuperUIUtil.initRecylerView(getContext(), rvFilterList, filterAdapter)
                .orientation(SuperUIUtil.RecycleViewManager.HORIZONTAL)
                .addItemDecoration(new SpacesItemDecoration(4))
                .onItemClick(new OnItemClickListener() {
                    @Override
                    public void onItemClick(View itemView, int viewType, int position) {
                        if (position == 0) {
                            filterImageView.setVisibility(View.GONE);
                        } else {
                            filterImageView.setVisibility(View.VISIBLE);
                            gpuImage.setFilter(filterAdapter.getData().get(position).filter());
                        }
                    }
                });

        // ------------------
        gpuImage = new GPUImage(getContext());
        gpuImage.setGLSurfaceView(filterImageView);
        //        noneBgBitmap = BitmapUtils.loadBitmapFromRaw(getContext(), R.drawable.filter1);
        //        gpuImage.setImage(noneBgBitmap); // this loads image on the current thread, should be run in a thread
        //        gpuImage.setFilter(MyFilterType.I_SIERRA.filter());
        setBitmap(originalBitmap, noneBgBitmap);
    } // initFilterViews

    @Override
    protected void initData() {

    }

    @OnClick({R.id.btn_filter, R.id.btn_sense, R.id.btn_close, R.id.btn_save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_sense:
                btnSense.setSelected(true);
                btnFilter.setSelected(false);
                break;
            case R.id.btn_filter:
                btnFilter.setSelected(true);
                btnSense.setSelected(false);
                break;
            case R.id.btn_close:
                if (from == 1) {
                    SceneManager.toScene(getContext(), TakeMemoryPhotoNewActivity.class, null);
                }
                getActivity().finish();
                break;
            case R.id.btn_save: // 保存处理结果图片
                ((BaseActivity) getActivity()).showLoading();
                if (currIndex == 0) {
                    uploadMixPhoto(originalBitmapLocalPath);
                } else {
                    final String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath()
                            + "/GPUImage/mixed.jpg";
                    if (FileUtil.isFileExsit(path)) {
                        FileUtil.deleteFile(path);
                    }
                    gpuImage.saveToPictures("GPUImage", "mixed.jpg", new GPUImage.OnPictureSavedListener() {
                        @Override
                        public void onPictureSaved(Uri uri) {
                            uploadMixPhoto(path);
                        }
                    });
                }
                break;
            default:
                break;
        }
    }

    // 接收外部照片
    public void setBitmap(Bitmap originalBitmap, Bitmap noneBgBitmap) {
        this.originalBitmap = originalBitmap;
        this.noneBgBitmap = noneBgBitmap;
        if (gpuImage != null && originalBitmap != null
            //                && noneBgBitmap != null
        ) {
            // 设置原图为背景列表第一个
            PhotoBgBean bgBean = new PhotoBgBean();
            bgBean.setOriginalBitmap(this.originalBitmap);
            bgListAdapter.getData().add(0, bgBean);
            bgListAdapter.notifyDataSetChanged();
            bgListAdapter.select(1);
        }
    }

    public void setMemPhotoBean(TryClothResultPhotoBean memPhotoBean) {
        this.memPhotoBean = memPhotoBean;
    }

    public void setOriginalBitmapLocalPath(String path) {
        this.originalBitmapLocalPath = path;
    }

    public void setFrom(int from) {
        this.from = from;
    }

    private void applyBgFilter(int position) {
        if (noneBgBitmap != null) {
            draggablePhotoView.setPhotoFrame(bgResourceIds[position], noneBgBitmap);
            draggablePhotoView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    updateFilterImage();
                    gpuImage.setFilter(getFilter(position));
                }
            }, 180);
        }
    }

    /**
     * 切换场景和滤镜
     *
     * @param btn
     * @param isSelected
     */
    @Override
    public void onSelect(BtnEffect btn, boolean isSelected) {
        switch (btn.getId()) {
            case R.id.btn_sense:
                btnSense.setSelected(true);
                btnFilter.setSelected(false);
                rvBgList.setVisibility(View.VISIBLE);
                rvFilterList.setVisibility(View.GONE);
                break;
            case R.id.btn_filter:
                btnSense.setSelected(false);
                btnFilter.setSelected(true);
                rvBgList.setVisibility(View.GONE);
                rvFilterList.setVisibility(View.VISIBLE);
                break;
            default:
                break;
        }
    }

    private GPUImageFilter getFilter(int position) {
        switch (position) {
            case 0:
                return MyFilterType.I_XPROII.filter();
            case 1:
                return MyFilterType.I_XPROII.filter();
            case 2:
                return MyFilterType.I_EARLYBIRD.filter();
            case 3:
                return MyFilterType.I_HEFE.filter();
            case 4:
                return MyFilterType.I_HEFE.filter();
            case 5:
                return MyFilterType.I_EARLYBIRD.filter();
            case 6:
                return MyFilterType.I_NASHVILLE.filter();
            case 7:
                return MyFilterType.I_INKWELL.filter();
            case 8:
                return MyFilterType.I_BRANNAN.filter();
            case 9:
                return MyFilterType.I_HEFE.filter();
            case 10:
                return MyFilterType.I_EARLYBIRD.filter();
            case 11:
                return MyFilterType.I_EARLYBIRD.filter();
            case 12:
                return MyFilterType.I_AMARO.filter();
            default:
                return MyFilterType.I_SIERRA.filter();
        }
    }

    private void uploadMixPhoto(String filePath) {
        Bitmap bitmap = BitmapUtils.loadBitmapFromFile(filePath);
        List<BasicNameValuePair> params = new ParamCreator()
                .add("userPhoto", BitmapUtils.bitmapToBase64(bitmap, 100))
                .add("photoNo", memPhotoBean == null ? UserUtil.getMemPhotoNo() : memPhotoBean.getPhotoNo())
                .add("backgroundName", bgListAdapter.getTitle(currIndex))
                .build();
        NetUtil.postObject(getContext(), NetConstants.URL.UPLOAD_MIX_PHOTO, params, new NetCallback<String>() {
            @Override
            public void onStart() {
            }

            @Override
            public void onSuccess(String result) {
                ((BaseActivity) getActivity()).hideLoading();
                if (from == 1) { // 来自拍照
                    EventBus.getDefault().post(new EventMessage(EventCode.CODE_UPDATE_MEMPHOTO_LIST, true));
                } else {
                    EventBus.getDefault().post(new EventMessage(EventCode.CODE_UPDATE_MEMPHOTO_LIST, false));
                }
                getActivity().finish();
            }

            @Override
            public void onFail(int errorCode, String errorMsg) {
                ((BaseActivity) getActivity()).hideLoading();
                TipUtil.show(errorMsg + errorCode);
            }
        });
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (noneBgBitmap != null && !noneBgBitmap.isRecycled()) {
            noneBgBitmap.recycle();
        }
        if (originalBitmap != null && !originalBitmap.isRecycled()) {
            originalBitmap.recycle();
        }
        if (twoValueBitmap != null && !twoValueBitmap.isRecycled()) {
            twoValueBitmap.recycle();
        }
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
        }
    }
}
